// pages/discover/discover.js
const app = getApp()

Page({
  data: {
    userInfo: null,
    filter: {
      gender: 'all',
      ageRange: [18, 35],
      distance: 50,
      tags: []
    },
    users: [],
    isLoading: false,
    hasMore: true,
    page: 1,
    showFilter: false
  },

  onLoad() {
    this.checkAuthAndLoadData();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
    }
  },

  onPullDownRefresh() {
    this.setData({ page: 1, users: [] });
    this.searchUsers().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.searchUsers(this.data.page + 1);
    }
  },

  // 检查授权并加载数据
  checkAuthAndLoadData() {
    if (app.globalData.userInfo) {
      this.setData({ userInfo: app.globalData.userInfo });
      this.searchUsers();
    } else {
      wx.redirectTo({
        url: '/pages/login/login'
      });
    }
  },

  // 搜索用户
  async searchUsers(page = 1) {
    if (this.data.isLoading) return;

    this.setData({ isLoading: true });

    try {
      const result = await wx.request({
        url: `${app.globalData.baseUrl}/users/search`,
        method: 'GET',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        },
        data: {
          page: page,
          limit: 10,
          gender: this.data.filter.gender === 'all' ? null : this.data.filter.gender,
          min_age: this.data.filter.ageRange[0],
          max_age: this.data.filter.ageRange[1],
          distance: this.data.filter.distance,
          tags: this.data.filter.tags.join(',')
        }
      });

      if (result.data.success) {
        const newUsers = result.data.data.users || [];
        const hasMore = result.data.data.has_more || false;

        this.setData({
          users: page === 1 ? newUsers : [...this.data.users, ...newUsers],
          hasMore: hasMore,
          page: page
        });
      } else {
        app.showError(result.data.message || '搜索失败');
      }
    } catch (error) {
      console.error('搜索用户失败:', error);
      app.showError('网络错误，请重试');
    } finally {
      this.setData({ isLoading: false });
    }
  },

  // 切换筛选面板
  toggleFilter() {
    this.setData({
      showFilter: !this.data.showFilter
    });
  },

  // 更新筛选条件
  updateFilter(e) {
    const { field, value } = e.currentTarget.dataset;
    const filter = { ...this.data.filter };
    
    if (field === 'ageRange') {
      filter.ageRange = value;
    } else if (field === 'tags') {
      if (filter.tags.includes(value)) {
        filter.tags = filter.tags.filter(tag => tag !== value);
      } else {
        filter.tags.push(value);
      }
    } else {
      filter[field] = value;
    }

    this.setData({ filter });
  },

  // 更新年龄最小值
  updateAgeMin(e) {
    const value = e.detail.value;
    const filter = { ...this.data.filter };
    filter.ageRange[0] = parseInt(value);
    this.setData({ filter });
  },

  // 更新年龄最大值
  updateAgeMax(e) {
    const value = e.detail.value;
    const filter = { ...this.data.filter };
    filter.ageRange[1] = parseInt(value);
    this.setData({ filter });
  },

  // 更新距离
  updateDistance(e) {
    const value = e.detail.value;
    const filter = { ...this.data.filter };
    filter.distance = parseInt(value);
    this.setData({ filter });
  },

  // 应用筛选
  applyFilter() {
    this.setData({
      showFilter: false,
      page: 1,
      users: []
    });
    this.searchUsers();
  },

  // 重置筛选
  resetFilter() {
    this.setData({
      filter: {
        gender: 'all',
        ageRange: [18, 35],
        distance: 50,
        tags: []
      },
      showFilter: false,
      page: 1,
      users: []
    });
    this.searchUsers();
  },

  // 喜欢用户
  async likeUser(e) {
    const userId = e.currentTarget.dataset.userId;
    
    try {
      const result = await wx.request({
        url: `${app.globalData.baseUrl}/matches/like`,
        method: 'POST',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        },
        data: { target_user_id: userId }
      });

      if (result.data.success) {
        app.showSuccess('喜欢成功');
        
        // 更新用户状态
        const users = this.data.users.map(user => {
          if (user.id === userId) {
            return { ...user, is_liked: true };
          }
          return user;
        });
        this.setData({ users });
        
        // 检查是否匹配成功
        if (result.data.data.is_match) {
          wx.showModal({
            title: '匹配成功！',
            content: '你们互相喜欢，可以开始聊天了',
            confirmText: '去聊天',
            cancelText: '继续浏览',
            success: (res) => {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/chat/chat'
                });
              }
            }
          });
        }
      } else {
        app.showError(result.data.message || '操作失败');
      }
    } catch (error) {
      console.error('喜欢用户失败:', error);
      app.showError('操作失败');
    }
  },

  // 查看用户详情
  viewUserDetail(e) {
    const userId = e.currentTarget.dataset.userId;
    wx.navigateTo({
      url: `/pages/user-detail/user-detail?id=${userId}`
    });
  },

  // 预览图片
  previewImage(e) {
    const urls = e.currentTarget.dataset.urls;
    const current = e.currentTarget.dataset.current;
    
    wx.previewImage({
      urls: urls,
      current: current
    });
  }
})
